//
//  OneMapViewController.m
//  DataStatistics
//
//  Created by oilklenze on 15/11/13.
//  Copyright © 2015年 YTYangK. All rights reserved.

//首页gps

#import "Annotation.h"
#import "CanlloutAnnotationView.h"
#import "JZLocationConverter.h"
#import "KCAnnotation.h"
#import "OneMapViewController.h"
#import "EquipmenDetailsVC.h"
#import "MapGPSViewController.h"
#import "RightViewController.h"
#import <pop/POP.h>
#import "MapGPSModel.h"
#import "OneMapGPSViewModel.h"
#import "CoverView.h"


@import AddressBookUI;
typedef void (^placemarks2)(NSDictionary* placemark);

@interface OneMapViewController () <MKMapViewDelegate, passDeviceCodeInMapView> {
    NSUInteger count; //设备图标记录按的台
    BOOL _firstDisplay; //是否第一loading
    DeviceListGps* listGps; //数据模型
    MKPolyline* line; // 地图出现的蓝色线
    NSString *GPS_recordChoiceDevice;
    CoverView *cover;
    NSString *key;
}

@property (strong, nonatomic) IBOutlet UIActivityIndicatorView* activity;
//@property (strong, nonatomic) EquipmentInformation  *equipmentInformation;
@property (strong, nonatomic) CLLocationManager* locationMangager; //定位
@property (nonatomic) CLLocationCoordinate2D coordinate; //地图坐标
@property (nonatomic, strong) UILabel* destination; //左下角label
@property (nonatomic, strong) NSArray* multipleAnnotationGrouds; //经过计算的距离小于10m的大头针集合结构是：[[arry],[arry].....]数组里面嵌套的数组，再嵌套的Annotation

@end

@implementation OneMapViewController

#pragma mark - 生命周期

- (void)viewDidLoad
{
    [self.activity startAnimating];
    [super viewDidLoad];
 
//    [self welcome];
    
    [self.tabBarController removeFromParentViewController];
    //    self.tabBarController.tabBar.hidden=YES;
    _firstDisplay = YES;
    _mapview.delegate = self;
    _locationMangager = [[CLLocationManager alloc] init];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addNewEquipment:) name:@"equipmentInformation" object:nil];

    
    _mapview.userTrackingMode = MKUserTrackingModeFollow;
    //地图类型
    _mapview.mapType = MKMapTypeStandard;
}


- (void)viewWillAppear:(BOOL)animated

{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];


    //开定位 低版本和高版本方法不一样
    if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
        [_locationMangager startUpdatingLocation];
    }
    else {
        
        [_locationMangager requestWhenInUseAuthorization];
        
    }

    //自己位置图标
    [self dataRequest];
    [self addmyLocation];

}


-(void)welcome
{
    cover = [[CoverView alloc]init];
    
    [cover setCoverObjectForKey:key = @"MapView"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapView)];
    
    [cover.DevicesView addGestureRecognizer:tap];

}


-(void)TapView
{
    [cover.DevicesView removeFromSuperview];
    
    [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:key];
    
}





#pragma mark - custom method
//权限判断
- (BOOL)authorizationStatus{
    if (!([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) && !([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        UIAlertController *authorizationStatusAler =[UtilToolsClss addAlertControllerForAuthorizationStatus:@"请打开系统设置中\"隐私->定位->服务\",允许\"Oilklenze\"使用您的位置"];
        [self presentViewController:authorizationStatusAler animated:YES completion:nil];
        return NO;
    }else {
        return YES;
    }
}


//数据处理并添加大头针
- (void)dataRequest
{
//    NSString* urlstr1 = [NSString stringWithFormat:@"deviceList/deviceListGps.asp?deviceCode"];
//    NSString* urlstr = [IPHEAD stringByAppendingString:urlstr1];
//    
//    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
//    NSDictionary* parameters = [[NSDictionary alloc] init];
//
//    
//    NSLog(@"urlstr =============== %@",urlstr);
//    
//    [manager POST:urlstr parameters:nil
//        success:^(AFHTTPRequestOperation* _Nonnull operation, id _Nonnull responseObject) {
//            if ([responseObject isKindOfClass:[NSDictionary class]]) {
//                listGps = [[DeviceListGps alloc] initWithDictionary:responseObject error:nil];
//                
//        NSLog(@"model520 ============  %@",responseObject);
//        NSLog(@"parameters ============  %@",parameters);
//
//                
//                [self.mapview removeAnnotations:self.mapview.annotations];
//                [self addAnnotation];
//            }
//        }
//        failure:^(AFHTTPRequestOperation* _Nullable operation, NSError* _Nonnull error) {
//            //网络请求错误直接退出
//            if (error.code == -1004) {
//                [MBProgressHUD showError:NET_ERROR];
//            }
//            else {
//                [MoreViewController logout:self];
//            }
//        }];
    
    
    
    
    [OneMapGPSViewModel requestWithUrlForLoginIn:self andParam:nil success:^(MapGPSModel *model) {
        
        
    listGps = [[DeviceListGps alloc] initWithDictionary:(id)model error:nil];


        [self.mapview removeAnnotations:self.mapview.annotations];

            NSMutableArray* annotations = [[NSMutableArray alloc] init];
        
        

            for (int i = 0; i < listGps.mapGPSModel.count; i++) {
                MapGPSModel* ppGpsModel = listGps.mapGPSModel[i];
                
                NSLog(@"modelhh ============   %@",ppGpsModel);

                
                Annotation* annotation = [[Annotation alloc] init];
                annotation.running_state = ppGpsModel.running_state;
                annotation.upload_time = ppGpsModel.upload_time;
                // JZLocationConverter 第三方库 进行WGS84转GCJ02类型的坐标
        
                CLLocationCoordinate2D Gcj02 = [JZLocationConverter wgs84ToGcj02:CLLocationCoordinate2DMake(ppGpsModel.latitude, ppGpsModel.longitude)];
                annotation.coordinate = Gcj02;
                annotation.c_name = ppGpsModel.c_name;
                annotation.deviceCode = ppGpsModel.deviceCode;
                annotation.index = i;
                if (Gcj02.latitude != 0.0f && Gcj02.longitude !=0.0f) {
                    [annotations addObject:annotation];
                }
            }
        
            //[self devicePath:self.mapview.annotations];
            count = annotations.count;
            //左下角的label 内容
            self.destination.text = [NSString stringWithFormat:NSLocalizedString(@"System Qty:%li", "总台数:"), (long)count];
            // getIntoGrouds 自定义方法  进行大头针距离分析
            // 返回一个数组里面是单个大头针（距离大于10m的），并为self.multipleAnnotationGrouds赋值！
            NSArray* singPlaceAnnotationsArry = [self getIntoGrouds:annotations];
            //  单个大头针数据分析 并添加到Map
            for (Annotation* annotation in singPlaceAnnotationsArry) {
                if (annotation.running_state == 1) {
                    annotation.icon = [UIImage imageNamed:@"在线标记"];
                }
                else {
                    annotation.icon = [UIImage imageNamed:@"离线标记"];
                }
        
                [self.mapview addAnnotation:annotation];
            }
            // 多个大头针 并添加到Map
            for (NSArray* grousAnnotation in self.multipleAnnotationGrouds) {
                Annotation* annotation = grousAnnotation[0];
                annotation.icon = [UIImage imageNamed:@"多台标记"];
                [self.mapview addAnnotations:grousAnnotation];
            }
            [self.activity stopAnimating];
            _firstDisplay ? [self.mapview showAnnotations:self.mapview.annotations animated:YES] :nil;
            _firstDisplay = NO;
        
        
        
    } failure:^(NSString *error) {
        
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
    }];
    
    
    
}



//数据处理并添加大头针
//- (void)addAnnotation
//{
//    NSMutableArray* annotations = [[NSMutableArray alloc] init];
//
//    for (int i = 0; i < listGps.ppGpsModel.count; i++) {
//        PPGpsModel* ppGpsModel = listGps.ppGpsModel[i];
//        Annotation* annotation = [[Annotation alloc] init];
//        annotation.running_state = ppGpsModel.running_state;
//        annotation.upload_time = ppGpsModel.upload_time;
//        // JZLocationConverter 第三方库 进行WGS84转GCJ02类型的坐标
//        
//        CLLocationCoordinate2D Gcj02 = [JZLocationConverter wgs84ToGcj02:CLLocationCoordinate2DMake(ppGpsModel.latitude, ppGpsModel.longitude)];
//        annotation.coordinate = Gcj02;
//        annotation.c_name = ppGpsModel.c_name;
//        annotation.deviceCode = ppGpsModel.deviceCode;
//        annotation.index = i;
//        if (Gcj02.latitude != 0.0f && Gcj02.longitude !=0.0f) {
//            [annotations addObject:annotation];
//        }
//    }
//
//    //[self devicePath:self.mapview.annotations];
//    count = annotations.count;
//    //左下角的label 内容
//    self.destination.text = [NSString stringWithFormat:NSLocalizedString(@"System Qty:%li", "总台数:"), (long)count];
//    // getIntoGrouds 自定义方法  进行大头针距离分析
//    // 返回一个数组里面是单个大头针（距离大于10m的），并为self.multipleAnnotationGrouds赋值！
//    NSArray* singPlaceAnnotationsArry = [self getIntoGrouds:annotations];
//    //  单个大头针数据分析 并添加到Map
//    for (Annotation* annotation in singPlaceAnnotationsArry) {
//        if (annotation.running_state == 1) {
//            annotation.icon = [UIImage imageNamed:@"在线标记"];
//        }
//        else {
//            annotation.icon = [UIImage imageNamed:@"离线标记"];
//        }
//
//        [self.mapview addAnnotation:annotation];
//    }
//    // 多个大头针 并添加到Map
//    for (NSArray* grousAnnotation in self.multipleAnnotationGrouds) {
//        Annotation* annotation = grousAnnotation[0];
//        annotation.icon = [UIImage imageNamed:@"多台标记"];
//        [self.mapview addAnnotations:grousAnnotation];
//    }
//    [self.activity stopAnimating];
//    _firstDisplay ? [self.mapview showAnnotations:self.mapview.annotations animated:YES] :nil;
//    _firstDisplay = NO;
//}


//设置定位自己按钮
- (void)addmyLocation

{
    UIButton* myLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [myLocation.layer  setCornerRadius:31];

    [myLocation setBackgroundImage:[UIImage imageNamed:@"标记按钮"] forState:UIControlStateNormal];

    [myLocation addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.mapview addSubview:myLocation];
    [myLocation mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.mapview).with.offset(10);
        make.bottom.equalTo(self.mapview).with.offset(-35);
        make.height.mas_equalTo(@62);
        make.width.mas_equalTo(@62);
    }];
}

//点击按钮显示自己位置
- (void)clickButton:(UIButton*)button

{
    if (!self.mapview.userLocation.location) {
        [self authorizationStatus];
    }else{
        CLLocationCoordinate2D coord = self.mapview.userLocation.coordinate;
        MKCoordinateSpan span = { 0.01, 0.01 };
        MKCoordinateRegion region = { coord, span };
        [self.mapview setRegion:region animated:YES];
    }

  
}

//添加路线显示线
- (void)routeLine:(Annotation*)annotation
{
    MKPlacemark* destinationPlaceMack = [[MKPlacemark alloc] initWithCoordinate:annotation.coordinate
                                                              addressDictionary:@{
                                                                  @"name" : @"设备"
                                                              }];
    MKMapItem* destinationItem = [[MKMapItem alloc] initWithPlacemark:destinationPlaceMack];
    MKMapItem* userItem = [MKMapItem mapItemForCurrentLocation];
    MKDirectionsRequest* request = [[MKDirectionsRequest alloc] init];
    request.source = userItem;
    request.destination = destinationItem;
    MKDirections* dirertion = [[MKDirections alloc] initWithRequest:request];
    [dirertion calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse* _Nullable response, NSError* _Nullable error) {
        for (MKRoute* route in response.routes) {
            if (line) {
                [self.mapview removeOverlay:line];
                line = nil;
            }
            line = route.polyline;
            [self.mapview addOverlay:line];
        }
    }];
}

//移除所用自定义大头针
- (void)removeCustomAnnotation
{
    [self.mapview.annotations enumerateObjectsUsingBlock:^(id<MKAnnotation> _Nonnull obj, NSUInteger idx,
                                  BOOL* _Nonnull stop) {
        if ([obj isKindOfClass:[KCAnnotation class]]) {
            [self.mapview removeAnnotation:obj];
        }
    }];
}
//计算大头针分类 小于10m 为一类 大于10m 不合并
- (NSArray*)getIntoGrouds:(NSMutableArray*)annotations
{
    for (int i = 0, b = 0; i < annotations.count; i++) {
        Annotation* annotationA = (Annotation*)annotations[i];
        for (int a = i + 1; a < annotations.count; a++) {
            Annotation* annotationB = (Annotation*)annotations[a];
            if ([self compareTowPlacesDistancewhetherOrNotLessTenMeter:annotationA another:annotationB]) {
                if (annotationA.sort == 0 && annotationB.sort == 0) {
                    b++;
                    annotationA.sort = [[NSNumber alloc] initWithInt:b];
                    annotationB.sort = annotationA.sort;
                }
                else if (annotationA.sort != 0 && annotationB.sort == 0) {
                    annotationB.sort = annotationA.sort;
                }
                else if (annotationA.sort == 0 && annotationB.sort != 0) {
                    annotationA.sort = annotationB.sort;
                }
                else if (annotationA.sort != 0 && annotationB.sort == 0) {
                    annotationB.sort = annotationA.sort;
                }
                else if (annotationA.sort != 0 && annotationB.sort != 0) {
                    if (annotationA.sort >= annotationB.sort) {
                        annotationA.sort = annotationB.sort;
                    }
                    else {
                        annotationB.sort = annotationA.sort;
                    }
                }
            }
        }
    }

    NSMutableArray* singlePlaceAnnotationsArry = [annotations mutableCopy];
    NSArray* sortedAnnotation = nil;
    NSMutableArray* tem = [[NSMutableArray alloc] init];
    for (Annotation* annotation in annotations) {
        if (annotation.sort) {
            [singlePlaceAnnotationsArry removeObject:annotation];
            [tem addObject:annotation];
        }
    }
    sortedAnnotation = [tem copy];
    sortedAnnotation = [sortedAnnotation
        sortedArrayUsingComparator:^NSComparisonResult(Annotation* a1, Annotation* a2) {
            return [a1.sort compare:a2.sort];
        }];
    NSMutableArray* arrayAll = [[NSMutableArray alloc] init];
    int location = 0;
    for (int i = 1; i < sortedAnnotation.count; i++) {
        Annotation* annotationB = sortedAnnotation[i];
        Annotation* annotationA = sortedAnnotation[i - 1];
        if (![annotationA.sort isEqualToNumber:annotationB.sort]) {
            NSRange rang;
            rang.location = location;
            rang.length = i - location;
            NSArray* arry = [sortedAnnotation subarrayWithRange:rang];
            [arrayAll addObject:arry];
            location = i;
        }

        if (i == sortedAnnotation.count - 1) {
            NSRange rang1;
            rang1.location = location;
            rang1.length = sortedAnnotation.count - location;
            NSArray* arry1 = [sortedAnnotation subarrayWithRange:rang1];
            [arrayAll addObject:arry1];
        }
    }

    NSArray* multipleAnnotationGrouds = [arrayAll copy];
    self.multipleAnnotationGrouds = multipleAnnotationGrouds;
    return singlePlaceAnnotationsArry;
}

#define PI 3.141592653
//计算两坐标的距离
- (BOOL)compareTowPlacesDistancewhetherOrNotLessTenMeter:(Annotation*)annotationA
                                                 another:(Annotation*)anotationB
{
    double er = 6378137; // 6378700.0f;
    // ave. radius = 6371.315 (someone said more accurate is 6366.707)
    // equatorial radius = 6378.388
    // nautical mile = 1.15078
    double radlat1 = PI * annotationA.coordinate.latitude / 180.0f;
    double radlat2 = PI * anotationB.coordinate.latitude / 180.0f;
    // now long.
    double radlong1 = PI * annotationA.coordinate.longitude / 180.0f;
    double radlong2 = PI * anotationB.coordinate.longitude / 180.0f;
    if (radlat1 < 0)
        radlat1 = PI / 2 + fabs(radlat1); // south
    if (radlat1 > 0)
        radlat1 = PI / 2 - fabs(radlat1); // north
    if (radlong1 < 0)
        radlong1 = PI * 2 - fabs(radlong1); // west
    if (radlat2 < 0)
        radlat2 = PI / 2 + fabs(radlat2); // south
    if (radlat2 > 0)
        radlat2 = PI / 2 - fabs(radlat2); // north
    if (radlong2 < 0)
        radlong2 = PI * 2 - fabs(radlong2); // west
    // spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    // zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2));
    // side, side, side, law of cosines and arccos
    double theta = acos((er * er + er * er - d * d) / (2 * er * er));
    double dist = theta * er;
    if (dist <= 10) {
        return YES;
    }
            
    else {
        return NO;
    }
}

//计算地图按像素位移
- (CLLocationCoordinate2D)mapCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate withOffsetXPixelSize:(CGSize)size
{
    CGFloat pixelsPexDegreeLet = SCREEN_HEIGHT-64-49 / self.mapview.region.span.latitudeDelta;
    CGFloat pixelsPerDegreeLon = SCREEN_WIDTH / self.mapview.region.span.longitudeDelta;
    
    CLLocationDegrees offsetLonDegree = size.width / pixelsPerDegreeLon;
    CLLocationDegrees offsetLatDegree = size.height / pixelsPexDegreeLet;
    CLLocationCoordinate2D newCoordinate = {
        centerCoordinate.latitude + offsetLatDegree,
        centerCoordinate.longitude + offsetLonDegree
    };
    return newCoordinate;
}

#pragma mark - delegate
#pragma mark MKMapViewDelegate
//地图控件代理方法显示大头针是调用  *****这个是自定义泡沫弹窗主要方法 和tabelview 添加cell 类似
- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id<MKAnnotation>)annotation

{
    //第一次加载大头针
    if ([annotation isKindOfClass:[Annotation class]]) {
        static NSString* identifier1 = @"CustAnnotation";
        MKAnnotationView* annotationView = [self.mapview dequeueReusableAnnotationViewWithIdentifier:identifier1];
        if (annotationView == nil) {
            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:identifier1];
        }

        annotationView.annotation = (Annotation*)annotation;
        annotationView.image = ((Annotation*)annotation).icon;
        annotationView.enabled = YES;
        annotationView.canShowCallout = NO;
//        annotationView.centerOffset = CGPointMake(0, -10); //-18
        return annotationView;
        //这个是点击加载判断
        //点击弹出泡沫框加载的大头针设置自定义泡沫和动画
    }
    else if ([annotation isKindOfClass:[KCAnnotation class]]) {
        CanlloutAnnotationView* annotationView = [[CanlloutAnnotationView alloc] initWithAnnotation:annotation
                                                                                    reuseIdentifier:@"hello"];
        annotationView.annotation = (KCAnnotation*)annotation;

        [annotationView initSubView];
        POPSpringAnimation* anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
        anim.fromValue = [NSValue valueWithCGRect:CGRectMake(-30 * 0.7, -10.25, 30, 8)];
        anim.toValue = [NSValue valueWithCGRect:CGRectMake(-300 * 0.71, -95, 300, 80)];
        anim.springBounciness = 10;
        anim.springSpeed = 5;
        [annotationView.view pop_addAnimation:anim forKey:nil];
        if (annotationView.annotation.sort) {
            [annotationView setMultipleLabelTextAndOnlineStats:self.multipleAnnotationGrouds];
        }
        else {
            [annotationView setSingleLabelText:(KCAnnotation*)annotation];
        }
        //        }];
        annotationView.centerOffset = CGPointMake(0, 0);
        annotationView.delegate = self;
        return annotationView;
    }
    //定位自己大头针
    else {
        return nil;
    }
}

// 更新自己位置时调用
- (void)mapView:(MKMapView*)mapView didUpdateUserLocation:(MKUserLocation*)userLocation
{
    
}

//  点击大头针弹出

//点击一般的大头针KCAnnotation时添加一个大头针作为所点大头针的弹出详情视图

- (void)mapView:(MKMapView*)mapView didSelectAnnotationView:(MKAnnotationView*)view
{
    
    //添加自定义大头针
    if ([view.annotation isKindOfClass:[Annotation class]]) {
        Annotation* annotation = (Annotation*)view.annotation;
        KCAnnotation* customAnnotation = [[KCAnnotation alloc] init];
        customAnnotation.upload_time = annotation.upload_time;
        customAnnotation.coordinate = annotation.coordinate;
        customAnnotation.c_name = annotation.c_name;
        customAnnotation.deviceCode = annotation.deviceCode;
        customAnnotation.index = annotation.index;
        customAnnotation.sort = annotation.sort;
        [self.mapview addAnnotation:customAnnotation];
    }

    //点击划线
    self.coordinate = view.annotation.coordinate;
    if ([view.annotation isKindOfClass:[Annotation class]]) {
        [self routeLine:(Annotation*)view.annotation];
    }
    self.addressView.address.text =nil;
    [self.addressView.activity startAnimating];
    [AddressView getAddressByLatitude:view.annotation.coordinate.latitude longitude:view.annotation.coordinate.longitude  addrees:^(NSString *placemark) {
        if (!placemark || ![placemark isEqualToString:@""]) {
            [self.addressView.activity stopAnimating];
        }
        [self.addressView.address setText:placemark];
        NSLog(@"---%@",placemark);
    }];
    [self.addressView addAppearAnimationByBeginFrame:self.addressView.frame finishFrame:CGRectMake(20, 0, self.addressView.size.width, self.addressView.size.height)];
    CLLocationCoordinate2D newCoordinate =     [self mapCenterCoordinate:view.annotation.coordinate withOffsetXPixelSize:CGSizeMake(-63, 0)];
    [self.mapview setCenterCoordinate:newCoordinate animated:YES];

    
    
    

}

//代理方法 设置路线样式

- (MKOverlayRenderer*)mapView:(MKMapView*)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    MKPolylineRenderer* render = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    render.strokeColor = RGB(14, 108, 255, 0.9);
    render.lineWidth = 5;
    return render;
}

//代理方法取消点击大头针后触发
- (void)mapView:(MKMapView*)mapView didDeselectAnnotationView:(MKAnnotationView*)view
{
    //移除自定义大头针
    [self removeCustomAnnotation];
    [self.mapview removeOverlay:line];
    line = nil;
    [self.addressView addAppearAnimationByBeginFrame:self.addressView.frame finishFrame:CGRectMake(20, -52 - 64, self.addressView.size.width, self.addressView.size.height)];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.addressView labelSetAddress:nil];
    });
}

//导航代码

#pragma mark--------导航弹出框
- (void)mapNavigationBtn:(UIButton*)button
{
    NSString* title = [NSString stringWithFormat:NSLocalizedString(@"导航到设备", nil) ];
    UIAlertController* alerController = [UIAlertController
        alertControllerWithTitle:title
                         message:nil
                  preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil)
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];
    UIAlertAction* gaodeMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"高德地图",nil)
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction* _Nonnull action) {

                                                               NSString* urlsting = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme=&lat=%f&lon=%f&dev=0&style=2", self.coordinate.latitude, self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                                                               [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];

                                                           }];

//    CLLocationCoordinate2D bd09 = [JZLocationConverter gcj02ToBd09:self.coordinate];
    UIAlertAction* baiduMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"百度地图",nil)
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction* _Nonnull action) {
                                                               NSString* urlsting = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02", self.coordinate.latitude, self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                                                               [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];
                                                           }];

    UIAlertAction* googleMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Google地图",nil)
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction* _Nonnull action) {
                                                                NSString* urlsting = [[NSString stringWithFormat:@"comgooglemaps://?x-source= &x-success=&saddr=&daddr=%f,%f&directionsmode=driving", self.coordinate.latitude, self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                                                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];
                                                            }];

    UIAlertAction* ownMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"自带地图",nil)
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction* _Nonnull action) {

                                                             MKMapItem* currentLocation = [MKMapItem mapItemForCurrentLocation];
                                                             MKMapItem* toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:self.coordinate addressDictionary:nil]];
                                                             [MKMapItem openMapsWithItems:@[ currentLocation, toLocation ] launchOptions:@{
                                                                 MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
                                                                 MKLaunchOptionsShowsTrafficKey : [NSNumber numberWithBool:YES]
                                                             }];
                                                         }];

    [alerController addAction:cancelAction];
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
        [alerController addAction:baiduMapAction];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [alerController addAction:gaodeMapAction];
    };
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        [alerController addAction:googleMapAction];
    }
    [alerController addAction:ownMapAction];

    if (objc_getClass("UIAlertController") != nil) {
        [self presentViewController:alerController animated:YES completion:nil];
    }
    else {
//        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
//                                                        message:@"请升级系统版本后用此功能"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil, nil];
////        [alert show];
    }
}

/**传人所以的大头针 计算并分组 1.返回数组里面装的是单个大头针 此处的大头针sort=0
                           2.赋值multipleAnnotationGrouds
   里面嵌套的是数组，每个数组里面的大头针sort是非0数字（sort=1 为一组 sort=2
   为一组 sort=3 为一组 类推），并且按小到大进行排列 [[arry],[arry].....]
   arry装的大头针
 */
#pragma mark passDeviceCodeInMapViewDelegate 自定义代理；
/*自定义代理方法  push页面
 *参数1 设备编号
 */

- (void)passDeviceCodeInMapView:(NSString*)DeviceCode
{
   // JournalList* journalList = [[JournalList alloc] init];
 //   journalList.journalDeviceCode = DeviceCode;
  //  journalList.hidesBottomBarWhenPushed = YES;
  //  [self.navigationController pushViewController:journalList animated:YES];
    
    GPS_recordChoiceDevice = [NSString stringWithFormat:@"%@",DeviceCode];
    
    [self performSegueWithIdentifier:@"gpsJumpJournalList" sender:self];
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ( [segue.identifier compare:@"gpsJumpJournalList"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:GPS_recordChoiceDevice forKey:@"journalDeviceCode"];
    }
}



/*自定义代理方法  弹出右侧TableView
 *参数1 单个大头针里面的 sort 属性 （sort=0表示单个大头其他的表示多个大头针
 *1表示在multipleAnnotationGrouds 下标为0的数组里面Grouds
 *2表示在multipleAnnotationGrouds 下标为1的数组里面Grouds  以此类推。。。）
 */

- (void)addTableViewInMapView:(NSNumber*)sort

{
    NSArray* annotations = nil;
    if ([self.multipleAnnotationGrouds[sort.intValue - 1] isKindOfClass:[NSArray class]]) {
        annotations = self.multipleAnnotationGrouds[sort.intValue - 1];
    }
    RightViewController* righVC = [[RightViewController alloc] init];
    righVC.delegate = self;
    [self addChildViewController:righVC];

    [righVC.view setBackgroundColor:RGB(25, 25, 25, 0)];
    righVC.annotations = annotations;
    UIView* vie = [[UIView alloc] init];
    vie.backgroundColor = [UIColor blackColor];
    [self.mapview addSubview:righVC.view];
    [righVC.view mas_makeConstraints:^(MASConstraintMaker* make) {
        make.edges.equalTo(self.mapview);
    }];
    righVC.tabelView.frame = CGRectMake(righVC.view.width, 0, righVC.view.width / 2, righVC.view.height);
    righVC.tempView.frame = CGRectMake(0, 0, righVC.view.width, righVC.view.height);
    [UIView animateWithDuration:0.3
        delay:0
        options:UIViewAnimationOptionLayoutSubviews
        animations:^{
            righVC.tempView.alpha = 0.6;
            righVC.tabelView.frame = CGRectMake(righVC.view.width / 2, 0, righVC.view.width / 2, righVC.view.height);
            righVC.tempView.frame = CGRectMake(0, 0, righVC.view.width / 2, righVC.view.height);
        }
        completion:^(BOOL finished){
        }];
}

//EquipmentInformationDelegate
//监听方法
- (void)addNewEquipment:(NSNotification*)equipment
{
    NSDictionary  *info = equipment.userInfo;
   // self.equipmentInformation = (EquipmentInformation *) [info objectForKey:@"equipmentInformation"];
  //  self.equipmentInformation.einfoDelegate = self;
    
}
// 请求数据？
- (void)dismissViewControllerWithDevicesVlue:(NSString *)Str
{
    [self dataRequest];
    
}



#pragma mark - getter setter方法

- (UILabel*)destination
{
    if (!_destination) {
        _destination = [[UILabel alloc] init];
        [self.mapview addSubview:_destination];
        _destination.textAlignment = NSTextAlignmentRight;
        _destination.textColor = RGB(1, 1, 1, 0.9);
        _destination.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
        [_destination mas_makeConstraints:^(MASConstraintMaker* make) {
            make.right.equalTo(self.mapview).with.offset(-10);
            make.left.equalTo(self.mapview).with.offset(100);
            make.bottom.equalTo(self.mapview).with.offset(-30);
            make.height.mas_equalTo(@50);
        }];
    }
    return _destination;
}

- (AddressView *)addressView
{
    if (!_addressView) {
        _addressView = [[AddressView alloc]init];
        _addressView.frame = CGRectMake(20, -52 - 64, SCREEN_WIDTH - 40, 52);
        [self.mapview addSubview:_addressView];
        [_addressView.navigationBtm addTarget:self action:@selector(mapNavigationBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _addressView;
}
//- (EquipmentInformation *)equipmentInformation
//{
//    if (!_equipmentInformation) {
//        _equipmentInformation  = [[EquipmentInformation alloc]init];
//    }
//    return _equipmentInformation;
//    
//}






@end
